package com.card.service.system;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.card.consts.ScoreSourceConsts;
import com.card.consts.SystemConsts;
import com.card.entity.manager.User;
import com.card.entity.manager.UserScore;
import com.card.entity.system.Card;
import com.card.entity.system.Customer;
import com.card.repository.ICardRepository;
import com.card.repository.ICustomerRepository;
import com.card.repository.IUserRepository;
import com.card.repository.IUserScoreRepository;
import com.card.result.Result;
import com.card.vo.CardVo;
import com.google.common.collect.Lists;

/**
 * ClassName: SystemService <br/>
 * Function: 导入资源. <br/>
 * date: 2018年12月14日 上午8:59:30 <br/>
 * 
 * @author lishuai11
 * @version
 * @since JDK 1.8
 */
@Service("systemService")
public class SystemService {

	private static final Logger logger = LoggerFactory.getLogger(GiftService.class);

	@Autowired
	private ICardRepository cardRepository;

	@Autowired
	private ICustomerRepository customerRepository;

	@Autowired
	private IUserRepository userRepository;

	@Autowired
	private IUserScoreRepository userScoreRepository;

	@Transactional
	public Result postCustomer(List<Customer> customers) {
		try {
			User user;
			UserScore userScore;
			List<Card> list;
			int score;
			for (Customer customer : customers) {
				customerRepository.save(customer);
				synchronized (SystemConsts.CLASS_LOCK) {
					user = findByMobileLike(customer.getCustomeMobile());
					// 用户注册了，加积分
					if (user != null) {
						list = cardRepository.findByCardCode(customer.getCardCode());
						if (list == null || list.isEmpty()) {
							return Result.fail(Result.CLIENT_ERROR, "卡编码不合法");
						} else {
							score = list.get(0).getCardScore();
							if (user.getInviteCode() != null && !user.getInviteCode().equals("")) {
								// 给邀请人加积分
								user = userRepository.findByInviteCode(user.getInviteCode()).get(0);
							}
							user.setTotalScore(user.getTotalScore() + score);
							userRepository.save(user);
							userScore = new UserScore(user.getUserId(), ScoreSourceConsts.ACTIVITY_OPENCARD, score,
									true);
							userScoreRepository.save(userScore);
						}
					}
				}
			}
			return Result.success("成功");
		} catch (Exception e) {
			logger.error("SystemService.postCustomer()方法异常{},{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	public Result cards() {
		try {
			return Result.success("成功", allCards());
		} catch (Exception e) {
			logger.error("SystemService.cards()方法异常{},{}", e.getMessage(), e);
			return Result.fail(Result.SERVER_ERROR, "服务器异常");
		}
	}

	private List<CardVo> allCards() {
		List<Card> cards = (List<Card>) cardRepository.findAll();
		List<CardVo> cardVos = Lists.newLinkedList();
		if (cards != null && !cards.isEmpty()) {
			cards.forEach(card -> {
				cardVos.add(new CardVo(card.getCardName(),card.getCardCode(),card.getCardDetail(),card.getCardScore()));
			});
		}
		return cardVos;
	}

	private User findByMobileLike(String mobile) {
		String pre = mobile.substring(0, 3);
		String tail = mobile.substring(7);
		List<User> users = userRepository.findByMobileLike(pre);
		if (users == null || users.isEmpty()) {
			return null;
		} else {
			String userMobile;
			for (User user : users) {
				userMobile = user.getMobile();
				if (userMobile.substring(7).equals(tail)) {
					return user;
				}
			}
			return null;
		}
	}

}
